package thread;

class MyBlockingDeque{
     //保存数据的本体
    private int []date = new int[1000];
    //有效元素的个数
    private int size = 0;
    //队头下标
    private int head = 0;
    //队尾下标
    private int tail = 0;
    //专门的锁对象
    private Object locker = new Object();

    //入队列
     public void put(int value) throws InterruptedException {
         synchronized (locker){
             if(size == date.length){
                 //return;
                 locker.wait();//针对哪个对象加锁就使用哪个对象wait
             }
             date[tail] = value;
             size++;

             //处理tail到达数组尾部的情况
             if(tail>= date.length){
                 tail = 0;
             }
             //不要忘记修改元素的个数
             size++;
             //put成功了之后就可以唤醒take中的等待操作
             locker.notify();
         }
    }

    //出队列
    public Integer take() throws InterruptedException {
         synchronized (locker){
             //判断队列为空的情况
             if(size == 0){
                 //return null;
                 locker.wait();
             }
             //取出head位置的元素
             int ret = date[head];
             head++;
             if(head >= date.length){
                 head = 0;
             }
             size--;
             //这里take成功了就可以唤醒put中的等待操作
             locker.notify();
             return ret;
         }
    }

}

public class demo22 {
    private static MyBlockingDeque queue = new MyBlockingDeque();

    public static void main(String[] args) {
        //实现一个简单的生产者消费者模型
        Thread producer = new Thread(()->{
            int num = 0;
            while (true){
                try {
                    System.out.println("生产了:"+num);
                    queue.put(num);
                    num++;
                    //当生产者生产的慢一些，消费者就得跟着生产者的步伐走
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        producer.start();


        Thread customer = new Thread(()->{
            while (true){
                try {
                    int num = queue.take();
                    System.out.println("消费了:"+num);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        customer.start();
    }
}
